<?php
declare (strict_types=1);

namespace app\api\controller;

use app\common\model\TourVisitor;
use ffhome\frame\controller\CrudController;

class Visitor extends CrudController
{
    protected $modelName = TourVisitor::MODEL_NAME;
    protected $alias = 'v';

    protected $defaultPageSize = 1000;
    protected $createByField = false;
    protected $updateByField = false;

    public function index()
    {
        return $this->indexOperate();
    }

    public function save(int $id = 0)
    {
        if (empty($id)) {
            $this->addOperate();
        } else {
            $row = $this->getModelInfo($id);
            $this->editOperate($row);
        }
    }

    protected function buildWhere(array $param): array
    {
        $where = parent::buildWhere($param);
        $where[] = ["{$this->alias}.user_id", '=', $this->getCurrentUserId()];
        return $where;
    }

    protected function getFilterFields(): array
    {
        return ['id', 'name', 'sex', 'birthday', 'mobile', 'type', 'credentials'];
    }

    protected function onBeforeAdd(array &$data)
    {
        $data['user_id'] = $this->getCurrentUserId();
        parent::onBeforeAdd($data);
    }

    protected function onBeforeDelete($id): array
    {
        $row = parent::onBeforeDelete($id);
        if ($row['user_id'] !== $this->getCurrentUserId()) {
            $this->error(lang('visitor.only_operate_owner_visitor'));
        }
        return $row;
    }

    public function detail(int $id)
    {
        $row = $this->getModelInfo($id);
        if ($row['user_id'] !== $this->getCurrentUserId()) {
            $this->error(lang('visitor.only_operate_owner_visitor'));
        }
        $this->json_result($row);
    }

    protected function getCurrentUserId()
    {
        return currentMember()['id'];
    }
}